// This is the main DLL file.

#include "stdafx.h"
#include "NativeUtilities.h"

int replace_chars(const char* instr, char* outstr, int size, char from, char to)
{
   int i = 0;
   while (instr + i && i < size)
   {
      *(outstr + i) = *(instr + i) == from ? to : *(instr + i);
      i++;
   }
   return i;
}

void CALLBACK OpenFileDialog(HWND hwnd, HINSTANCE hinst, LPCSTR lpszCmdLine, int nCmdShow)
{
   std::string param;
   std::vector<std::string> commands;
   std::istringstream cmdStm(lpszCmdLine);

   while(std::getline(cmdStm, param, '?')) commands.push_back(param);

   HWND h;
   std::string title;
   std::string init_dir;
   std::string filters;

   try
   {
      h = (HWND)(void*)atol(commands.at(0).c_str());
      title = commands.at(1);
      init_dir = commands.at(2);
      filters = commands.at(3).c_str();
   }
   catch(...)
   {
      MessageBoxA(NULL, "Invalid parameters provided.", NULL, 1);
      printf("Error: invalid parameters provided.");
      return;
   }

   int length = filters.length();
   char *_filters = new char[length + 2];
   replace_chars(filters.c_str(), _filters, length + 2, '|', '\0');
   _filters[length] = 0;
   _filters[length + 1] = 0;

   char path[1024];
   OPENFILENAME ofn;
   ZeroMemory(&ofn, sizeof(ofn));
   ofn.lStructSize = sizeof(ofn);
   ofn.hwndOwner = h;
   ofn.lpstrFile = path;
   ofn.lpstrFile[0] = 0;
   ofn.nMaxFile = sizeof(path);
   ofn.lpstrFileTitle = NULL;
   ofn.nMaxFileTitle = 0;
   ofn.lpstrTitle = (char*)title.c_str();
   ofn.lpstrFilter = _filters;
   ofn.nFilterIndex = 0;
   ofn.lpstrInitialDir = (char*)init_dir.c_str();
   ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER;

   LONG r = GetOpenFileName(&ofn);

   delete [] _filters;

   std::string s("");

   if (r)
   {
      char _path[1024];
      memset(_path, 0, 1024);
      replace_chars(path, _path, 1024, '\0', ';');

      std::string p(_path);
      s = (p.substr(0, p.find(";;")));
   }

   HKEY hKey;
   r = RegCreateKeyEx(HKEY_CURRENT_USER,
                     "Software\\Microsoft\\OpenFileDialog",
                     0L,
                     NULL,
                     REG_OPTION_NON_VOLATILE,
                     KEY_ALL_ACCESS, NULL,
                     &hKey,
                     NULL);

   if (r == ERROR_SUCCESS)
   {
      RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)s.data(), s.length() + 1);
   }
   else
   {
      cout << "Unable to write registry.\r\n" << s.data();
   }
}